﻿using Daemon.Model;
using Microsoft.AspNetCore.Mvc;
using Daemon.Common;
using Daemon.Repository.Contract;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using ThoughtWorks.QRCode;
using ThoughtWorks.QRCode.Codec;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.Text;

namespace DaemonAPI
{
	[ApiController]
	[Route("api/[controller]/[action]")]
	public class HelperController : BaseApiController
	{
		private readonly IClientConfigRepository _clientConfigRepository;

		private readonly IConfiguration _configuration;

		public HelperController(IClientConfigRepository clientConfigRepository, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
		{
			_clientConfigRepository = clientConfigRepository;
			_configuration = configuration;
		}

		[HttpGet]
		[Route("")]
		public ResultModel GenerateCode(int boardId)
		{
			var baseUrl = _clientConfigRepository.Find()?.QrCodeBaseUrl;
			var path = GetFileAddress()?.FileAddress;
			var encoder = new QRCodeEncoder();
			encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
			encoder.QRCodeScale = 4;
			encoder.QRCodeVersion = 0;
			encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
			encoder.QRCodeBackgroundColor = Color.White;
			encoder.QRCodeForegroundColor = Color.Green;
			Bitmap bcodeBitmap = encoder.Encode($"{baseUrl}?boardId={boardId}", Encoding.UTF8);
			DirFile.CreateDirectory($"{path}/QrCode");
			SaveFileToDir($"{path}/QrCode/{boardId}.jpg", BitmapToBytes(bcodeBitmap));
			return new ResultModel(HttpStatusCode.OK, null, new List<string>() { $"{_configuration.GetSection("AppSettings:fileBaseUrl")?.Value}/Daemon/QrCode/{boardId}.jpg" });
		}

		private ClientConfig GetFileAddress()
		{
			var sysInfo = _clientConfigRepository.FindAll().FirstOrDefault();
			return sysInfo;
		}

		private void SaveFileToDir(string filePath, byte[] buffer)
		{
			using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
			{
				fs.Write(buffer, 0, buffer.Length);
			}
		}

		private byte[] BitmapToBytes(Bitmap bitmap)
		{
			MemoryStream ms = new MemoryStream();
			bitmap.Save(ms, ImageFormat.Bmp);
			ms.Seek(0, SeekOrigin.Begin);
			byte[] bytes = new byte[ms.Length];
			ms.Read(bytes, 0, bytes.Length);
			ms.Dispose();
			return bytes;
		}
	}
}
